(function() {
  var $addSwitchField = $('#add-switch-field');
  var $addedSwitchList = $('#added-switch-list');
  var $advancedSettingHeader = $('#advanced-switch-header');
  var $userDataFolderField = $('#user-data-dir');
  
  var as = window.AdvancedSetting = {
    exclusionSwitches: ['--user-data-dir', '--icon-id', '--load-extension'],
    
    setup: function() {
      $advancedSettingHeader.on('click', function() {
        var $userDataPath = $('#user-data-path-section');
        var arrow = 'hide';
        if ($userDataPath.css('display') == 'none') {
          $userDataPath.show();
          $('#advanced-switch-wrapper').show();
          $('#advanced-switch-header').css('border-bottom', '');
          arrow = 'show';
        } else {
          $userDataPath.hide();
          as.hide();
        }
        $('#advanced-switch-header > img').attr('src', 'images/' + arrow +
          '.png');
      });


      $('#select-user-data-dir-btn').on('click', function() {
        var path = Fs.selectPath(i18n['select_user_data_folder'],
          $userDataFolderField.val());
        if (path) {
          as.setUserDataFolder(path);
        }
      });

      $('#add-switch-form').on('submit', function(e) {
        e.preventDefault();
        var addSwitchField = $addSwitchField.get();
        var _switch = $addSwitchField.val().trim();
        if (!_switch) {
          Tip.alertField(addSwitchField, 'switch_required');
          addSwitchField.focus();
          return;
        }
        
        _switch = _switch.split('=');
        var switchId = _switch[0];
        var param = _switch[1];
        var validateResult = as.validateSwitch(switchId);
        $.log('Switch validation result: ' + validateResult);

        if (validateResult != 'ok') {
          Tip.alertField(addSwitchField, 'switch_' + validateResult);
          addSwitchField.focus();
          return false;
        }

        as.addSwitch(switchId, param);
        $addSwitchField.val('');
      });
    },

    init: function() {
      as.hide();
      $('#advanced-switch-header > img').attr('src', 'images/hide.png');
      $('#user-data-dir').val('');
      $('#add-switch-field').val('');
      as.clearSwitchList();
    },
  
    hide: function() {
      $('#advanced-switch-wrapper').hide();
      $('#user-data-path-section').hide();
      $('#advanced-switch-header').css('border-bottom', 'none');
    },

    setUserDataFolder: function(folder) {
      $userDataFolderField.val(folder);
    },

    getUserDataFolder: function() {
      return $userDataFolderField.val();
    },

    generateUserDataFolder: function(shortcutId) {
      var separator;
      if (isWindowsPlatform())
        separator = WIN_PATH_SEPARATOR;
      else
        separator = LINUX_PATH_SEPARATOR;
      return Fs.folderOfUsersData + separator + shortcutId;
    },

    validateUserDataFolder: function() {
      var folder = as.getUserDataFolder();
      var shortcutId = ShortcutSetting.modifiedShortcutId;
      if (folder == as.generateUserDataFolder(shortcutId))
        return true;
      if (folder == '') {
        Tip.alertField($userDataFolderField.get(), 'required_user_data_folder');
        $userDataFolderField.get().focus();
        return false;
      }
      if (/^"|"$/.test(folder) || !Fs.validatePath(folder)) {
        Tip.alertField($userDataFolderField.get(), 'invalid_user_data_folder');
        $userDataFolderField.get().focus();
        return false;
      }
      return true;
    },
    
    addSwitch: function(switchId, parameter) {
      var li = document.createElement('li');
      $(li).attr('id', switchId);
      li.innerHTML = $('#advanced-switch-item-template').html();
      var $switchItem = $('span.switch-item', li);
      var switchText = parameter ? switchId + '=' + parameter : switchId;
      $switchItem.text(switchText).attr('title', switchText);
      $('span.delete-switch', li).on('click', function() {
        as.removeSwitch(switchId, true);
      });
      $addedSwitchList.append(li).show();
    },

    getEnabledSwitches: function() {
      var enabledSwitches = {};
      $('.switch-item', $addedSwitchList).each(function(switchItem) {
        var _switch = $(switchItem).text().split('=');
        var parameter = '';
        if (_switch.length > 1)
          parameter = _switch[1];
        enabledSwitches[_switch[0]] = parameter;
      });

      return enabledSwitches;
    },

    removeSwitch: function(id, noConfirm) {
      if (noConfirm || Tip.confirm('confirm_to_delete_switch')) {
        $addedSwitchList.removeChild($id(id));
        if (!$addedSwitchList.get().childElementCount)
          $addedSwitchList.hide();
      }
    },

    validateSwitch: function(id) {
      if (!/^--[a-z]+(-[a-z0-9]+)*(=.+)?$/.test(id))
        return 'bad_format';
      if ($id(id))
        return 'duplicate';

      // Check if the switch is default added for implementing some feature of
      // extension, like --user-data-dir, --load-extensions etc.
      if (as.exclusionSwitches.indexOf(id) >= 0)
        return 'exclusive';

      // Check if it's existent in the switch list
      if (!Switches.switches[id.slice(2)])
        return 'nonexistent';
      return 'ok';
    },

    clearSwitchList: function() {
      $addedSwitchList.hide().html('');
    },

    applyShortcutData: function(shortcut) {
      var switches = shortcut.switches;
      var userDataFolder = shortcut.userDataFolder;

      as.setUserDataFolder(userDataFolder);
      for (var _switch in switches) {
        if (as.exclusionSwitches.indexOf(_switch) < 0)
          as.addSwitch(_switch, switches[_switch]);
      }
    },

    generateShortcutData: function() {
      return {
        userDataFolder: as.getUserDataFolder(),
        switches: as.getEnabledSwitches()
      };
    }
  };
})();